<template>
    <div class="latest_news">
        <div class="news">
            <div>
                <el-button type="primary" style="margin-top: 1px;" @click="addGoods()">+新增资讯</el-button>
            </div>
            <div class="operation_news">
                <span class="delect-intent" style="color: #000c17;font-weight: bold;" v-if="moreDelectId.length" @click="batchDelet">删除 <i class="el-icon-delete"></i></span>
                <span class="delect-intent" style="cursor: no-drop;" v-else >删除 <i class="el-icon-delete"></i></span>
            </div>
            <!--    新闻列表    -->
            <el-table
                    :data="tableData"
                    style="width: 100%"
                    :row-class-name="tableRowClassName"
                    @selection-change="selectFun">
                <el-table-column
                        type="selection"
                        width="50">
                </el-table-column>
                <el-table-column
                        prop="id"
                        label="编号"
                        width="50"
                        align="center">
                </el-table-column>
                <el-table-column
                        prop="news_title"
                        label="资讯名"
                        width="280"
                        align="center">
                </el-table-column>
                <el-table-column
                        prop="news_url"
                        label="地址"
                        align="center">
                    <template slot-scope="scope">
                            <a :href="scope.row.news_url" target="_blank"> {{scope.row.news_url}}</a>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="news_img"
                        label="宣传图"
                        width="150"
                        align="center">
                    <template slot-scope="scope">
                        <el-image
                                style="width: 100%; height: 100%"
                                :src="scope.row.news_img"
                                fit="fit">
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作">
                    <template slot-scope="scope">
                        <el-button type="text" @click="changeNews(scope.row)">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!--    分页    -->
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20, 30]"
                    :page-size="size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
<!--   新增新闻列表   -->
      <div class="add_news">
        <el-drawer
            :title="title"
            :visible.sync="drawer"
            :direction="direction"
            :before-close="handleClose">

          <div class="add_box_input">
            <div class="title_value">资讯信息：</div>
            <p style="padding-right: 5px;font-size: 14px;">
              <span class="symbol">*</span> 资讯名：<el-input placeholder="请输入资讯名字" v-model="name" clearable></el-input>
              <br/><br/>
              <span class="symbol">*</span> 地址：<el-input placeholder="请输入地址（http开头）" v-model="address" clearable></el-input>
              <br/><br/>
              <br/><br/>
            </p>
            <div class="title_value">上传宣传图：
              <el-upload
                  ref="upload"
                  class="upload-demo"
                  drag
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :http-request="uploadVideo"
                  multiple
                  :limit="1"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能上传jpg、png文件，且不超过10mb</div>
              </el-upload>
            </div>

            <div style="float: right;padding-right: 10px;">
              <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="change" v-if="checkSubmit">修改</el-button>
                <el-button type="primary" @click="submit" v-else>确定</el-button>
            </div>
          </div>

        </el-drawer>
      </div>
    </div>
</template>

<script>
import {newsInformationApi,addNewsApi,deleteNewsApi,changeNewsApi} from '@/api/zhy_port/demo'
import OSS from "ali-oss";
    export default {
        name: "index",
        data(){
            return{
                title:'新增资讯',
                checkSubmit:0,
                changId:'',
              tableData: [],
              moreDelectId:[],
              currentPage:1,
              size:10,
              total:0,
              drawer: false,
              direction: 'rtl',
              name:'',
              address:'',
              imgUrl:'',
            }
        },
        methods: {
            change(){
                let row = {
                    "id":this.changId,
                    "news_title":this.name,
                    "news_url":this.address,
                    "news_img":this.imgUrl
                }
                if (this.name !=='' && this.address !=='')
                {
                    //    资讯修改
                    changeNewsApi(row).then(() =>{
                        this.name ='';this.address='';this.imgUrl='';
                        this.$message({type: 'success', message: '修改成功!'});
                        this.$refs.upload.clearFiles();
                        this.news();
                        this.drawer = false;
                    });
                }else{
                    this.$message({type: 'info', message: '请填写完整!'});
                }
            },
            openDrawer(row,index){
                if (index){
                    this.title = '资讯详情';
                    this.name = row.news_title;
                    this.address = row.news_url;
                    this.changId = row.id;
                    this.imgUrl = row.news_img;
                    this.checkSubmit = index
                }else {
                    this.title = '新增资讯';
                    this.name = '';
                    this.address = '';
                    this.imgUrl = '';
                    this.checkSubmit=0;
                }
                this.drawer = true;
            },
            changeNews(row){
                this.openDrawer(row,1);
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            selectFun(selection){
                this.moreDelectId = selection;
                console.log(this.moreDelectId);
            },
            batchDelet(){
              this.check();
            },
          check(){
            let arrayId= [];
            for (let i=0;i< this.moreDelectId.length;i++)
            {
              arrayId.push(this.moreDelectId[i].id);
            }
            deleteNewsApi(arrayId).then(()=>{
              this.news();
              this.$message({type: 'success', message: '删除成功!'});
            })
          },
            addGoods(){
               this.openDrawer()
            },
            //    分页方法
            handleSizeChange(val) {
              this.size = val;
              this.currentPage = 1;
              this.news();

            },
            handleCurrentChange(val) {
                this.currentPage = val;
              this.news();

            },

          submit(){
            let row = {
              "news_title":this.name,
              "news_url":this.address,
              "news_img":this.imgUrl
            }
            if (this.name !=='' && this.address !=='')
            {
              //    资讯--添加
              addNewsApi(row).then(() =>{
                this.name ='';this.address='';this.imgUrl='';
                this.$message({type: 'success', message: '添加成功!'});
                this.$refs.upload.clearFiles();
                this.news();
                this.drawer = false;
              });
            }else{
              this.$message({type: 'info', message: '请填写完整!'});
            }
          },
          handleClose() {
            this.$confirm('确认关闭？')
                .then(_ => {
                  this.drawer = false;
                })
          },
          async uploadVideo(options){
            console.log(options.file.name);
            let fileName = options.file.name.lastIndexOf(".");//获取到文件名开始到最后一个“.”的长度。
            let fileNameLength = options.file.name.length;//获取到文件名长度
            let fileFormat = options.file.name.substring(fileName + 1, fileNameLength);//截取后缀名
            const client = new OSS({
              region: 'oss-cn-chengdu',
              accessKeyId: 'LTAI4G7xLwyqhsbHHEr77sDa',
              accessKeySecret: 'tXuM1SF5aD04od2pFOXDbJupsZ1M2q',
              bucket: 'yangshen520'
            });
            let name = Date.now()+'.' + fileFormat;
            let url ="https://yangshen520.oss-cn-chengdu.aliyuncs.com/" + name;
            try {
              await client.put(name, options.file,(res)=>{
                console.log(res);
              });
              console.log(url);
            } catch (e) {
              this.$message.error('上传失败')
            }
            this.imgUrl = url
          },
          news(){
            newsInformationApi(this.currentPage,this.size).then(req =>{
              console.log(req.data)
              this.total = req.data.totalElements;
              this.tableData=req.data.content;
            })
          },
        },
      created() {
        this.news();
      },
    }
</script>

<style lang="scss" scoped>
    .latest_news{
        .news{
            height: 550px;
            overflow: auto;
        }
        .news::-webkit-scrollbar {
            width: 4px;
            scrollbar-arrow-color:red;
        }
        .block{
            text-align: center;
        }
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
        .operation_news{
            height: 50px;
            width: 100%;
            .delect-intent{
                font-size: 16px;
                color: #c0c4cc;
                letter-spacing: 0.56px;
                line-height: 60px;
                margin-left: 40px;
                cursor: pointer;
            }
        }
      .add_news{
        /deep/.el-drawer__header{
          font-size: 20px !important;
          color: #000c17;
          font-weight: bold;
        }
        /deep/.el-drawer{
          width: 30% !important;
        }
        /deep/.el-upload-dragger{
          height: 100px !important;
          .el-icon-upload{
            margin-top: 10px;
            font-size: 50px;
          }
          .el-upload__text{
            margin-top: -10px;
          }
        }
        .add_box_input{
          margin-left: 20px;
          .title_value{
            font-size: 16px;
            font-weight: bold;
          }
          .symbol{
            font-weight: bold;
            color: red;
          }
        }
      }
    }
</style>
